define(window.backboneCommon.getViewDefine("creative.detail"), function ($,require,Collection,tpl,ViewSpace,ViewMaterial) {
    var backboneView= Backbone.View.extend({
        events: {
            "change #txt_apkId": "changeApkId",
            "click #btn_select_space": "selectSpace",
            "click #tb_listSpaces .spaces-delete": "deleteSpaces",
            "click #btn_submitSave": "submitSave"
        },
        initialize: function () {
            this.modelAttach={};
            this.modelAttach.baseData=this.model.get("modelBaseData");
            this.modelAttach.campaign=this.model.get("modelCampaign");
            this.modelAttach.spread=this.model.get("modelSpread");
            this.modelAttach.space=this.model.get("modelSpace");
            this.listenTo(this.modelAttach.baseData, "bind:ObjMatterType", this.bindObjMatterType);
            this.listenTo(this.modelAttach.baseData, "bind:ChannelPack", this.bindChannelPack);
            this.listenTo(this.modelAttach.campaign, "bind:Info", this.bindCampaign);
            this.listenTo(this.modelAttach.spread, "bind:AllList", this.bindSpread);
            this.listenTo(this.modelAttach.space, "bind:MaterialInfo", this.bindMaterial);
            this.listenTo(this.model, "bind:Info", this.bindInfo);
            this.listenTo(this.model, "save:Info", this.saveInfoCallback);
            this.render();
        },
        render:function(){
            var templateHtml=_.template(tpl);
            this.$el.html(templateHtml());
            return this;
        },
        initMain:function(param){
            var campaignId=param[0];
            if(campaignId){
                this.elementModel={};
                this.extObject={};
                this.pageData={
                    campaignId:campaignId,creativeId:param[1],
                    spaceSelect:{},materialInfo:{}
                };
                this.pageData.initSpreadId=$.ExtCommon.getQueryStringByHash("spread");
                this.initViewAttach();
                this._initPagePower();
            }else{
                $.ExtAssist.goUrlHref("#campaign");
            }
        },
        _initPagePower:function(){
            var self=this;
            $.ExtAssist.rolePower.operatePage("select",["edit","create"],function(json){
                self.pageData.power={
                    isOnlyView:json["select"],
                    isEdit:json["edit"],
                    isCreate:json["create"]
                };
                if(!self.pageData.power.isCreate && $.ExtCommon.isCheckEmpty(self.pageData.creativeId)){
                    $.ExtAssist.goUrlHref(self._getGoCampaignInfoUrl(),true);
                }else {
                    if (self.pageData.power.isEdit) {self.pageData.power.isOnlyView = false}
                    self._initBodyMain();
                }
            });
        },
        _initBodyMain:function(){
            this.elementModel.form=$("#form_detail");
            this.elementModel.interactive=$("#panel_interactive");
            this.elementModel.pChannelPack=$("#panel_channelPack");
            this.elementModel.tbSpaces=$("#tb_listSpaces");
            this.elementModel.material=$("#panel_material");
            this.collection.getCampaign(this.pageData.campaignId);

        },
        initViewAttach:function () {
            var self=this;
            self.viewAttach={};
            self.viewAttach.space=new ViewSpace({pElement:"#container_space",campaignId:self.pageData.campaignId,
                submitCallback:function(json){
                    if($.ExtCommon.isCheckEmpty(self.pageData.spaceSelect)||self.pageData.spaceSelect.id!==json.id){
                        self._bindSpaceTable(json);
                        self._changeSpace(json.id);
                    }
                }
            });
            self.viewAttach.material=new ViewMaterial({pElement:"#container_material", parentElementId:"#panel_material",
                campaignId:self.pageData.campaignId,url:self.modelAttach.baseData.get("defUploadImgUrl"),
                uploadImgCallback:function (element) {
                    self.elementModel.form.ExtParsley().validate(element);
                }
            });
        },

        bindCampaign:function () {
            var result=this.modelAttach.campaign.get("dataInfo");
            if(result.res.success){
                var name=result.res.data.name;
                var campaignInfoUrl=this._getGoCampaignInfoUrl();
                $.ExtAssist.navBread.nav([{name:"投放管理"},{name:"订单管理",href:"#campaign"},{name:name,href:campaignInfoUrl,cls:"ellipsis-txt-title"},{name:"创意详情"}]);
                $(".go-campaign-info").attr("href",this._getGoCampaignInfoUrl());
                $.ExtAssist.urlParam.setUrl();
                this.collection.getInfo(this.pageData.creativeId);
            }
        },
        _getGoCampaignInfoUrl:function () {
            return $.ExtCommon.getStringConnect("#campaign/{0}?tabs=2",this.pageData.campaignId);
        },

        bindInfo:function () {
            var self=this;
            var result=this.model.get("dataInfo");
            self.pageData.isAdd=result.isAdd;
            var operateName="";
            if(self.pageData.isAdd){operateName="新建"}
            else{operateName=self.pageData.power.isOnlyView?"查看":"编辑"}
            $.ExtAssist.navBread.title($.ExtCommon.getStringConnect("{0}创意",operateName));
            if(self.pageData.isAdd){
                if(!$.ExtCommon.isCheckEmpty(self.pageData.initSpreadId)){
                    result.res.data.spread=self.pageData.initSpreadId;
                }
            }
            self.extObject.formValue=self.elementModel.form.ExtFormValue({initValue:result.res.data,
                initCallback:function(dataJson){
                    self._initChannelPack();
                    self.collection.initAfterDetail(self.pageData.campaignId);
                    self.pageData.creativeInfo=dataJson;
                    self.viewAttach.material.initValue(dataJson.materialList,dataJson.materialJson);
                    if(self.pageData.isAdd){
                        $("#btn_select_space").prop("disabled", $.ExtCommon.isCheckEmpty(dataJson.spread));
                        $(".operate-change-space").hide();
                        self.elementModel.tbSpaces.parent().hide();
                    }else{
                        if(dataJson.isAndroid){
                            self._getChannelPackData({objMatterType:dataJson.objMatterType,apkId:dataJson.apkId,initValue:dataJson.channelPack})
                        }
                        $("#btn_select_space").prop("disabled", true).hide();
                        self._bindSpaceTable(dataJson.space);
                        self._changeSpace(dataJson.spaceId);
                    }
                    if(self.pageData.power.isOnlyView){
                        self.elementModel.form.find(":text,textarea").prop("disabled", true);
                        $("#btnGoReturn").text("返回");
                    }
                    self.elementModel.form.ExtParsley();
                }
            });
            if (!result.res.success) {$.ExtNotify.error("该创意数据获取失败：" +result.res.msg)}
        },
        bindSpread:function () {
            var self=this;
            var res=this.modelAttach.spread.get("dataAllList");
            self.extObject.spread= $("#ddl_spread").ExtSelect2({placeholder: "-请选择-",minimumResultsForSearch: 1,infoExt: {data: res.data,
                initCallback: function () {
                    var info=self.extObject.spread.getValueInfo();
                    if(!$.ExtCommon.isCheckEmpty(info)){
                        self.checkInitMatterType(function () {
                            var info=self.extObject.spread.getValueInfo();
                            self._replaceMatterTypeData(info);
                        });
                    }
                    if(!self.pageData.isAdd) {self.extObject.spread.disabled()}
                    if(self.pageData.power.isOnlyView){self.extObject.spread.disabled()}
                },
                changeCallback: function (value, element,info) {
                    self.elementModel.form.ExtParsley().validate(element);
                    self._changeSpace();
                    var type=info.type.toString();
                    if(type===self.pageData.lastSpreadType){
                        this.extObject.objMatterType.setValue(info.objMatterType);
                    }else{
                        self._replaceMatterTypeData(info);
                    }
                    $("#btn_select_space").prop("disabled", false);
                    self._bindSpaceTable({});
                }
            }});
        },

        //标的物
        _getMatterTypeBySpread:function (spreadId) {
            if($.ExtCommon.isCheckUndefined(spreadId)){
                return this.pageData.ObjMatterType.list;
            }else{
                return this.pageData.ObjMatterType.group[spreadId.toString()]
            }
        },
        checkInitMatterType:function (cb) {
            var self=this;
            if(self.extObject.objMatterType){cb()
            }else{
                setTimeout(function () {
                    self.checkInitMatterType(cb);
                },100)
            }
        },
        _replaceMatterTypeData:function (info) {
            var list=this._getMatterTypeBySpread(info.type);
            $.each(list,function (i,info) {info.disabled=true;});
            this.extObject.objMatterType.replaceData(list);
            this.extObject.objMatterType.setValue(info.objMatterType);
            this.pageData.lastSpreadType=info.type;
        },
        bindObjMatterType:function () {
            var self=this;
            var res=self.modelAttach.baseData.get("dataObjMatterType");
            this.pageData.ObjMatterType=res.data;
            var list=this._getMatterTypeBySpread();
            $.each(list,function (i,info) {info.disabled=true;});
            this.extObject.objMatterType=$("#panel_objMatterType").ExtRadioCheckbox({type: "radio",attrName:"objMatterType",initIndex:0,data:list,
                initCallback:function () {
                    self.extObject.objMatterType.disabledAll();
                    self.changeObjMatterType();
                    if(self.pageData.power.isOnlyView){self.extObject.objMatterType.disabledAll()}
                },
                changeCallback:function () {
                    self.changeObjMatterType();
                    self._changeMaterialByObjMatter();
                }
            });
        },
        changeObjMatterType:function () {
            var info=this.extObject.objMatterType.getValueInfo();
            var type="ordinary";
            if(info.isOrdinary){type="ordinary"}
            else if(info.isAndroid){type="android"}
            else if(info.isIos){type="ios"}
            else if(info.isWeChat){type="weChat"}
            this.elementModel.interactive.find(".matter-type").hide().find(":text").removeAttr("required");
            this.elementModel.interactive.find(".matter-type-"+type).show().find(":text").attr("required","");
            if(type==="android"){
                var apkId=$("#txt_apkId").val();
                this.elementModel.pChannelPack.find(".loader-inner").hide();
                this.elementModel.pChannelPack.toggle(!$.ExtCommon.isCheckEmpty(apkId));
            }
        },

        changeApkId:function (e) {
            var apkId= $.trim($(e.currentTarget).val());
            this._getChannelPackData({objMatterType:this.extObject.objMatterType.getValue(),apkId:apkId,initValue:-1});
        },
        _getChannelPackData:function (param) {
            if(!$.ExtCommon.isCheckEmpty(param.apkId)){
                param.campaignId=this.pageData.campaignId;
                this.elementModel.pChannelPack.show().find(".loader-inner").show();
                this.extObject.channelPack.replaceData([{id:"-1",text:"正在获取数据,请稍后……"}],"-1");
                this.extObject.channelPack.disabled();
                this.collection.getChannelPack(param);
            }else{
                this.elementModel.pChannelPack.hide();
                this.extObject.channelPack.replaceData([],-1);
            }
        },
        _initChannelPack:function () {
            var self=this;
            this.extObject.channelPack= $("#ddl_channelPack").ExtSelect2({placeholder: "-请选择-",allowClear: true,minimumResultsForSearch: 1,infoExt: {data: [],
                initCallback:function () {
                    if(self.pageData.power.isOnlyView){self.extObject.channelPack.disabled()}
                }
            }});
        },
        bindChannelPack:function () {
            var result=this.modelAttach.baseData.get("dataChannelPack");
            if(result.res.success){
                var initValue=result.req.initValue;
                this.extObject.channelPack.replaceData(result.res.data, initValue);
                if(this.pageData.power.isEdit){
                    this.extObject.channelPack.removeDisabled();
                }else if(this.pageData.power.isOnlyView){
                    this.extObject.channelPack.disabled();
                }
                this.elementModel.pChannelPack.find(".loader-inner").hide();
            }else{
                $.ExtNotify.error("获取渠道包数据失败："+result.res.msg);
            }
        },

        //广告位
        selectSpace:function () {
            var spread= this.extObject.spread.getValue();
            if(!$.ExtCommon.isCheckEmpty(spread)) {
                this.viewAttach.space.init(this.pageData.spaceSelect,{spreadId: spread})
            }
        },
        deleteSpaces:function () {
            this._bindSpaceTable({});
            this._changeSpace()
        },
        _bindSpaceTable:function (jsonData) {
            var self=this;
            var isEmpty=$.ExtCommon.isCheckEmpty(jsonData);
            if (isEmpty) {
                self.elementModel.tbSpaces.find("tbody tr").remove();
                self.elementModel.tbSpaces.parent().hide();
            } else {
                self.elementModel.tbSpaces.parent().show();
                if (self.extObject.tbSpaces){self.extObject.tbSpaces.destroy()}
                var options={
                    paging: false,
                    serverSide: false,
                    bInfo: false,
                    columns: [
                        {data: "id", class: "w-60"},
                        {data: "name", class: "w-min-100"},
                        {data: "adFormat", class: "w-80"},
                        {data: "media", class: "w-80"},
                        {data: "platform", class: "w-80"},
                        {data: "describe", class: "w-150"},
                        {data: null, class: "w-60 text-center"}
                    ],
                    infoExt: {data: [jsonData]},
                    createdRow: function (row,data) {
                        var elementTd=$("td", row);
                        elementTd.eq(5).html($.ExtCommon.getStringConnect('<div class="ellipsis-txt-title w-150" title="{0}">{0}</div>',[data.describe]));
                        if(self.pageData.isAdd){ elementTd.eq(6).html('<a class="btn-operate spaces-delete" href="javascript:">删除</a>')}
                    },
                    drawCallback: function () {}
                };
                options.columns[6]["visible"]=self.pageData.isAdd;
                self.extObject.tbSpaces = self.elementModel.tbSpaces.ExtDataTable(options);
            }
            self.pageData.spaceSelect=jsonData;
        },
        _changeSpace:function (spaceId) {
            if($.ExtCommon.isCheckEmpty(spaceId)){
                this.hideMaterial();
            }else{
                this.collection.getMaterialInfo(spaceId);
            }
        },

        //素材
        bindMaterial:function () {
            $.ExtNotify.destroy();
            var self=this;
            var res=this.modelAttach.space.get("dataMaterialInfo");
            if(res.success){
                this.pageData.materialInfo=res.data;
                if($.ExtCommon.isCheckEmpty(this.pageData.materialInfo.sampleUrl)){
                    $("#img_sampleUrl").removeAttr("src").parents(".form-group:first").hide();
                }else{
                    $("#img_sampleUrl").attr("src",this.pageData.materialInfo.sampleUrl).parents(".form-group:first").show();
                }
                if(this.pageData.materialInfo.list.length>0){
                    if(this.pageData.materialInfo.isNative){
                        self.checkInitMatterType(function () {
                            var objMatterIfo=self.extObject.objMatterType.getValueInfo();
                            self.viewAttach.material.initNative({list:self.pageData.materialInfo.list,filter:objMatterIfo.matterTypeFilter,isDisabled:self.pageData.power.isOnlyView});
                            self._checkShowMaterial()
                        });
                    }else{
                        this.viewAttach.material.initDefault({list:this.pageData.materialInfo.list,isDisabled:this.pageData.power.isOnlyView});
                        this._checkShowMaterial()
                    }
                }else{
                    $.ExtNotify.error("该广告位的暂无素材数据");
                    this._hideMaterialTemp();
                }
            }else{
                this.pageData.materialInfo={};
                $.ExtNotify.error("该广告位的素材数据获取失败：" +res.msg);
                this.hideMaterial();
            }
        },
        _checkShowMaterial:function () {
            if(this.elementModel.material.children().length>0){
                this.elementModel.material.parents(".form-group:first").show();
            }else{
                this._hideMaterialTemp();
            }
        },
        _hideMaterialTemp:function () {
            this.elementModel.material.parents(".form-group:first").hide();
        },
        _changeMaterialByObjMatter:function () {
            if(!$.ExtCommon.isCheckEmpty(this.pageData.materialInfo.list) && this.pageData.materialInfo.isNative){
                var info=this.extObject.objMatterType.getValueInfo();
                this.viewAttach.material.initFilter(info.matterTypeFilter);
            }
        },
        hideMaterial:function () {
            $(".operate-change-space").hide();
            $("#img_sampleUrl").removeAttr("src");
            this.elementModel.material.html("");
            this.pageData.materialInfo={};
        },

        _checkForm:function(data){
            $.ExtNotify.destroy();
            var isExtCheck=true;
            if($.ExtCommon.isCheckEmpty(data.space)){
                isExtCheck=false;
                $.ExtNotify.error("请选择广告位");
            }else{
                if(data.isNative){
                    var checkNative=this.viewAttach.material.checkNative();
                    isExtCheck=checkNative.length===0;
                }else{
                    isExtCheck=this.viewAttach.material.checkDefault();
                }
            }
            return this.elementModel.form.ExtParsley("validate") && isExtCheck;
        },
        submitSave:function () {
            var ajaxData = this.elementModel.form.ExtFormValue("getValues");
            ajaxData.space=this.pageData.spaceSelect.id;
            ajaxData.isNative=this.pageData.materialInfo.isNative;
            if(this._checkForm(ajaxData)) {
                ajaxData.materialList=ajaxData.isNative?this.viewAttach.material.getValueNative():this.viewAttach.material.getValueDefault();
                ajaxData.spread=parseInt(ajaxData.spread);
                ajaxData.campaignId=parseInt(this.pageData.campaignId);
                ajaxData.templateId=this.pageData.materialInfo.template;
                ajaxData.adFormat=parseInt(this.pageData.materialInfo.adFormat);
                ajaxData.objMatterType=parseInt(ajaxData.objMatterType);
                ajaxData.matterTypeInfo=this.extObject.objMatterType.getValueInfo();
                var infoOriginal = this.elementModel.form.ExtFormValue("getOriginalData");
                if (infoOriginal.id) {ajaxData.id = infoOriginal.id}
                this.collection.saveInfo(ajaxData);
            }
        },
        saveInfoCallback:function () {
            var result=this.model.get("dataSave");
            if (result.res.success) {
                $.ExtNotify.success("保存成功!");
                $.ExtAssist.goUrlHref(this._getGoCampaignInfoUrl());
            }else{
                $.ExtNotify.error(result.res.msg);
            }
        }
    });
    var viewModel=function(){
        this.collection= new Collection();
        this.model=this.collection.model;
        this.view=new backboneView({el: "#container_bodyMain",collection:this.collection,model:this.model});
    };
    viewModel.prototype={
        initView:function (param) {
            this.view.initMain(param);
        }
    };
    return viewModel;
});